<template>
  <div class="login-box">
    <el-card class="box-card header">
      <div slot="header" class="clearfix">
        <span>黑马面经运营后台</span>
      </div>
      <!-- form -->
      <el-form label-width="80px" :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="form.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="form.password"
            type="password"
            @keyup.enter.native="login"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="login"
            :loading="flag"
            class="loginBtn"
            >登录</el-button
          >
          <el-button type="default" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from '@/api/user'
// import store from '@/store'

export default {
  name: 'login-page',
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入5-11位字符', trigger: 'blur' },
          {
            pattern: /^[a-z]{5,11}$/,
            message: '请输入5-11位字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入5-11位字符', trigger: 'blur' },
          {
            pattern: /^[a-z]{5,11}$/,
            message: '请输入5-11位字符',
            trigger: 'blur'
          }
        ]
      },
      flag: false
    }
  },
  methods: {
    async login() {
      try {
        await this.$refs.form.validate()
        this.flag = true
        // 发请求
        const res = await login(this.form)
        console.log(res)
        console.log(res.data.token)
        this.$store.commit('user/setUserToken', res.data.token)
        this.flag = false
        this.$router.push('/')
      } catch (err) {
        console.log(err)
        if (err.response && err.response.status === 400) {
          this.$message.error('用户名或密码错误')
        } else {
          this.$message.error('表单校验失败')
          this.flag = false
        }
      }
    },
    reset() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped lang="scss">
.login-box {
  height: 100vh;
  background: url('@/assets/login-bg.svg') no-repeat center / cover;
  display: flex;
  justify-content: center;
  align-items: center;
  .header {
    width: 422px;

    text-align: center;
    color: #fff;
  }
  ::v-deep .el-card__header {
    background-color: #737eed;
  }
  .loginBtn {
    background-color: #737eed;
  }
}
</style>
